﻿


using Mrc.Data;
using System;
using System.Collections.Generic;
using System.Text;
using Mrc.Entity;
using Chloe;
using System.Linq.Expressions;
using System.Linq;
using DotNetEx;

namespace Mrc.Application
{
    public interface ISysRoleService : IServiceBase<SysRole>, IMrcService
    {
        List<SysRole> GetRoles(string keyword = "");
        void Delete(string roleId, string operatorId);
        List<SysRole> GetList(string keyword = "");
        List<SysRolePermission> GetPermissions(string id);
        void SetPermission(string id, List<string> permissionList);


    }
    public class SysRoleService : ServiceBase<SysRole>, ISysRoleService
    {
        public SysRoleService(IDbContext dbContext, IServiceProvider services) : base(dbContext, services)
        {

        }

        public List<SysRole> GetRoles(string keyword = "")
        {
            var q = this.DbContext.Query<SysRole>().FilterDeleted();
            if (keyword.IsNotNullOrEmpty())
            {
                q = q.Where(a => a.Name.Contains(keyword));
            }

            var ret = q.OrderBy(a => a.SortCode).ToList();
            return ret;
        }

        public void Delete(string id, string operatorId)
        {
            this.DbContext.SoftDelete<SysRole>(id, operatorId);
        }


        public List<SysRole> GetList(string keyword = "")
        {
            var q = this.DbContext.Query<SysRole>().FilterDeleted();
            q = q.Where(a => a.Name.Contains(keyword));
            var ret = q.OrderBy(a => a.SortCode).ToList();
            return ret;
        }
        public List<SysRolePermission> GetPermissions(string id)
        {
            return this.DbContext.Query<SysRolePermission>().Where(t => t.RoleId == id).ToList();
        }
        public void SetPermission(string id, List<string> permissionList)
        {
            List<SysRolePermission> roleAuths = permissionList.Select(a => new SysRolePermission()
            {
                Id = IdHelper.CreateStringSnowflakeId(),
                RoleId = id,
                PermissionId = a
            }).ToList();
            this.DbContext.DoWithTransaction(() =>
            {
                this.DbContext.Delete<SysRolePermission>(a => a.RoleId == id);
                this.DbContext.InsertRange(roleAuths);
            });
        }
    }
}
